package com.mes.controller;

import com.mes.constant.ResponseStatus;
import com.mes.mapper.MaterialsMapper;
import com.mes.mapper.OrderMapper;
import com.mes.po.Materials;
import com.mes.po.Order;
import com.mes.po.Product;
import com.mes.service.IBaseService;
import com.mes.service.IProductService;
import com.mes.util.MesResponse;
import com.mes.util.TableResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@RestController
@RequestMapping("/product")
public class ProductController extends BaseController<Product> {


    @Autowired
    private IProductService productService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private MaterialsMapper materialsMapper;
    @Override
    IBaseService<Product> getService() {
        return productService;
    }

    @RequestMapping(value = "/getAllProducts", method = RequestMethod.GET)
    @ResponseBody
    public TableResponse<Product> getAllProducts(Integer page, Integer limit, Integer productId,
                                                 String productCode,String productQuality) {
        TableResponse<Product> response = new TableResponse<>(ResponseStatus.SUCESS, "查询成功！");
        List<Product> itemList = productService.selectProductByQuality(page, limit, productId, productCode,productQuality);
        Integer countRole = productService.countItem();
        response.setData(itemList);
        response.setCount(countRole);
        return response;
    }

    @RequestMapping(value = "/addProduct", method = RequestMethod.POST)
    @ResponseBody
    public MesResponse addProduct(Product product) {
        if(product.getProductStatus().equals("0")){
            // 减计划
            Order order = orderMapper.selectByPrimaryKey(product.getOrderId());
            order.setProductNum(order.getProductNum()-1);
            orderMapper.updateByPrimaryKeySelective(order);
        }
        // 减物料
        Materials materials = materialsMapper.selectByPrimaryKey(product.getMaterialsId());
        materials.setMaterialsNum(materials.getMaterialsNum() - product.getMaterialsNum());
        materialsMapper.updateByPrimaryKey(materials);
        // 加产品
        product.setCreateTime(new Date());
        return addItem(product);
    }


    @RequestMapping(value = "/updateProduct", method = RequestMethod.POST)
    @ResponseBody
    public MesResponse updateProduct(Product product) {
        return updateItem(product);
    }

    @RequestMapping(value = "/deleteProduct", method = RequestMethod.POST)
    @ResponseBody
    public MesResponse deleteOperation(int productId) {
        return deleteItem(productId);
    }
}
